import React from 'react';
import { Layout, List, Typography, Space, Button, Tag, Popconfirm, message } from 'antd';
import { MenuUnfoldOutlined, MenuFoldOutlined, AppstoreOutlined, HomeOutlined, DeleteOutlined } from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import { ExperimentRun, ExperimentFullData } from '../../types';
import { formatDate } from '../../utils/formatUtils';
import { experimentApi } from '../../services/api';

const { Sider } = Layout;
const { Text, Paragraph } = Typography;

interface ExperimentListProps {
  experiments: ExperimentRun[];
  selectedExperiment: ExperimentFullData | null;
  onSelectExperiment: (experiment: ExperimentRun) => void;
  onClearSelection?: () => void;
  collapsed?: boolean;
  onCollapseChange?: (collapsed: boolean) => void;
  onRefresh?: () => void;
  onRemoveExperiment?: (experimentId: number) => void;
  projectNameEn?: string;
}

const ExperimentList: React.FC<ExperimentListProps> = ({
  experiments,
  selectedExperiment,
  onSelectExperiment,
  onClearSelection,
  collapsed = false,
  onCollapseChange,
  onRefresh,
  onRemoveExperiment,
  projectNameEn,
}) => {
  const navigate = useNavigate();
  const params = useParams<{ projectId: string }>();
  const projectId = projectNameEn || params.projectId;
  const siderWidth = collapsed ? 64 : 300;
  
  // 使用 ref 跟踪正在删除的实验ID，防止在删除过程中选择该实验
  const deletingExperimentIdRef = React.useRef<number | null>(null);

  const handleCollapse = () => {
    onCollapseChange?.(!collapsed);
  };

  const handleHome = () => {
    // 回到当前页面的首页，清空选中的实验
    onClearSelection?.();
  };

  const handleDelete = async (experiment: ExperimentRun) => {
    if (!projectId) {
      message.error('项目信息缺失');
      return;
    }

    const experimentId = experiment.id;
    
    // 标记该实验正在删除中
    deletingExperimentIdRef.current = experimentId;
    
    // 如果删除的是当前选中的实验，立即清空选择（在删除请求之前）
    if (selectedExperiment?.id === experimentId) {
      onClearSelection?.();
    }

    // 立即从列表中移除该实验（乐观更新），避免用户在刷新前点击已删除的实验
    onRemoveExperiment?.(experimentId);

    try {
      await experimentApi.deleteExperiment(projectId, experimentId);
      message.success('删除成功');
      
      // 刷新列表以保持数据同步（此时已删除的实验不会再在列表中，也不会被选中）
      await onRefresh?.();
    } catch (error: any) {
      console.error('Failed to delete experiment:', error);
      message.error(error.response?.data?.detail || '删除失败');
      // 如果删除失败，重新刷新列表以恢复状态
      await onRefresh?.();
    } finally {
      // 清除删除标记
      deletingExperimentIdRef.current = null;
    }
  };
  
  // 处理实验选择，添加删除检查
  const handleSelectExperiment = (experiment: ExperimentRun) => {
    // 如果该实验正在删除中，不执行选择操作
    if (deletingExperimentIdRef.current === experiment.id) {
      return;
    }
    
    // 检查实验是否还在列表中（防止点击已删除的实验）
    const stillExists = experiments.some(exp => exp.id === experiment.id);
    if (stillExists) {
      onSelectExperiment(experiment);
    }
  };

  return (
    <Sider
      width={siderWidth}
      style={{
        background: '#fff',
        borderRight: '1px solid #f0f0f0',
        overflow: 'hidden',
        height: '100vh',
        position: 'fixed',
        left: 0,
        top: 0,
        bottom: 0,
        transition: 'width 0.2s',
        display: 'flex',
        flexDirection: 'column',
        zIndex: 100
      }}
    >
      {/* 上半部分：功能按钮区域 */}
      <div style={{ 
        padding: '12px',
        borderBottom: '1px solid #f0f0f0',
        flexShrink: 0,
        overflow: 'hidden'
      }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
          <div style={{ display: 'flex', gap: '8px', alignItems: 'center', justifyContent: 'space-between' }}>
            {collapsed ? (
              <Button
                type="text"
                icon={<MenuUnfoldOutlined />}
                onClick={handleCollapse}
                title="展开侧边栏"
                style={{ 
                  width: '32px',
                  height: '32px',
                  padding: '0',
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  flexShrink: 0
                }}
              />
            ) : (
              <>
                <Button
                  type="text"
                  icon={<HomeOutlined />}
                  onClick={handleHome}
                  style={{ 
                    width: 'auto',
                    height: '32px',
                    padding: '4px 8px',
                    paddingLeft: '4px',
                    display: 'flex',
                    justifyContent: 'flex-start',
                    alignItems: 'center',
                    flexShrink: 0
                  }}
                  title="首页"
                >
                  <span style={{ marginLeft: '8px' }}>首页</span>
                </Button>
                <Button
                  type="text"
                  icon={<MenuFoldOutlined />}
                  onClick={handleCollapse}
                  title="收起侧边栏"
                  style={{ 
                    width: '32px',
                    height: '32px',
                    padding: '4px 0',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    flexShrink: 0
                  }}
                />
              </>
            )}
          </div>
          <Button
            type="text"
            icon={<AppstoreOutlined />}
            onClick={() => navigate('/')}
            style={{ 
              width: collapsed ? '32px' : 'auto',
              height: '32px',
              padding: '4px',
              paddingLeft: '4px',
              paddingRight: collapsed ? '4px' : '8px',
              display: 'flex',
              justifyContent: 'flex-start',
              alignItems: 'center',
              flexShrink: 0
            }}
            title="参数系统"
          >
            {!collapsed && <span style={{ marginLeft: '8px' }}>参数系统</span>}
          </Button>
        </div>
      </div>

      {/* 下半部分：实验结果列表 */}
      {!collapsed && (
        <div 
          style={{ 
            flex: '1 1 auto',
            minHeight: 0,
            height: '100%',
            display: 'flex',
            flexDirection: 'column',
            overflow: 'hidden'
          }}
        >
          {/* 实验结果标题 - 固定不滚动 */}
          <div 
            style={{ 
              flexShrink: 0,
              padding: '12px 16px', 
              borderBottom: '1px solid #f0f0f0',
              backgroundColor: '#fff'
            }}
          >
            <Text strong style={{ fontSize: '14px' }}>实验结果</Text>
          </div>
          
          {/* 实验列表 - 可滚动区域 */}
          <div 
            style={{ 
              flex: '1 1 auto',
              minHeight: 0,
              overflowY: 'auto',
              overflowX: 'hidden',
              WebkitOverflowScrolling: 'touch'
            }}
          >
            <List
              dataSource={experiments}
              locale={{ emptyText: '暂无实验记录' }}
              style={{ 
                padding: 0,
                backgroundColor: '#fff'
              }}
              renderItem={(experiment) => (
                <List.Item
                  style={{
                    cursor: 'pointer',
                    padding: '12px 16px',
                    borderBottom: '1px solid #f0f0f0',
                    background: selectedExperiment?.id === experiment.id ? '#e6f7ff' : '#fff',
                    transition: 'background 0.2s'
                  }}
                  onClick={() => handleSelectExperiment(experiment)}
                  actions={[
                    <Popconfirm
                      title="确定要删除这个实验结果吗？"
                      description="删除后无法恢复，所有相关数据将被永久删除。"
                      onConfirm={() => {
                        handleDelete(experiment);
                      }}
                      okText="确定"
                      cancelText="取消"
                      key="delete"
                      onCancel={(e) => {
                        // 取消时阻止事件冒泡
                        e?.stopPropagation?.();
                      }}
                    >
                      <Button
                        type="text"
                        danger
                        size="small"
                        icon={<DeleteOutlined />}
                        onClick={(e) => {
                          e.stopPropagation();
                        }}
                        style={{ opacity: 0.6 }}
                        title="删除实验"
                      />
                    </Popconfirm>
                  ]}
                >
                  <List.Item.Meta
                    title={
                      <div>
                        <Space>
                          <Tag color="blue" style={{ margin: 0 }}>
                            {experiment.id}
                          </Tag>
                          <Text strong>{experiment.name || `实验 #${experiment.id}`}</Text>
                        </Space>
                      </div>
                    }
                    description={
                      <div>
                        <div style={{ marginTop: 4, fontSize: '12px', color: '#999' }}>
                          {formatDate(experiment.created_at)}
                        </div>
                        {experiment.description && (
                          <Paragraph
                            ellipsis={{ rows: 2 }}
                            style={{ marginTop: 4, marginBottom: 0, fontSize: '12px' }}
                          >
                            {experiment.description}
                          </Paragraph>
                        )}
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          </div>
        </div>
      )}
    </Sider>
  );
};

export default ExperimentList;

